package io.gitee.hefren.hhconfig.server.controller;

import io.gitee.hefren.hhconfig.server.beans.Configs;
import io.gitee.hefren.hhconfig.server.conf.DistributedLock;
import io.gitee.hefren.hhconfig.server.service.HhConfigServerService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.List;
import java.util.Map;

/**
 * @Date 2024/5/26
 * @Author lifei
 */
@RestController
@RequestMapping(value = "/hhConfigServerController")
public class HhConfigServerController {

    @Resource
    private DistributedLock distributedLock;
    @Resource
    private HhConfigServerService hhConfigServerService;

    /**
     * 查询 capp_cenv_cnamespace 的参数列表
     * @param capp
     * @param cenv
     * @param cnamespace
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<Configs> list(@RequestParam("capp") String capp,
                              @RequestParam("cenv") String cenv,
                              @RequestParam("cnamespace") String cnamespace) {
        return hhConfigServerService.findConfigsList(capp, cenv, cnamespace);
    }

    /**
     * 更新或插入 capp_cenv_cnamespace 的配置值
     * @param capp
     * @param cenv
     * @param cnamespace
     * @param kvMap
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public List<Configs> update(@RequestParam("capp") String capp,
                                @RequestParam("cenv") String cenv,
                                @RequestParam("cnamespace") String cnamespace,
                                @RequestBody Map<String, String> kvMap) {
        return hhConfigServerService.updateOrInsertConfigsList(capp, cenv, cnamespace, kvMap);
    }

    /**
     * 查询 capp_cenv_cnamespace 的版本
     * @param capp
     * @param cenv
     * @param cnamespace
     * @return
     */
    @RequestMapping(value = "/version", method = RequestMethod.GET)
    public Long version(@RequestParam("capp") String capp,
                        @RequestParam("cenv") String cenv,
                        @RequestParam("cnamespace") String cnamespace) {
        return hhConfigServerService.findConfigsVersion(capp, cenv, cnamespace);
    }


    @RequestMapping(value = "/deferredResultVersion", method = RequestMethod.GET)
    public DeferredResult<Long> deferredResultVersion(@RequestParam("capp") String capp,
                                  @RequestParam("cenv") String cenv,
                                  @RequestParam("cnamespace") String cnamespace) {
        return hhConfigServerService.deferredResultVersion(capp, cenv, cnamespace);
    }

    @RequestMapping(value = "/status", method = RequestMethod.GET)
    public Boolean status() {
        return distributedLock.getLock();
    }

}
